package de.schnocklake.android.sap.crm.datamodel;

import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;

import org.dom4j.Document;
import org.dom4j.DocumentFactory;
import org.dom4j.Element;
import org.dom4j.Node;

import android.util.Log;
import de.schnocklake.android.soap.SoapException;
import de.schnocklake.android.soap.SoapUtils;

public class Quotation {
	protected String endpoint = "http://crm.esworkplace.sap.com:80/sap/bc/srt/xip/sap/CRM_BTSQ_CUSTQTECRTCHKQR?sap-client=800";
	protected String username = "S0004428881";
	protected String password = "Mantila1";

	String id;
	Customer customer;
	String processingTypeCode;
	HashMap<Integer, Item> items;
	int lastItemId = 0;

	public Quotation() {
		super();
		this.customer = null;
		this.processingTypeCode = "AG";
		this.items = new HashMap<Integer, Item>();
	}

	public Item appendNewItem() {
		lastItemId = lastItemId + 10;
		Item newItem = new Item(lastItemId);
		this.items.put(newItem.getId(), newItem);
		return newItem;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public Customer getCustomer() {
		return customer;
	}

	public void setCustomer(Customer customer) {
		this.customer = customer;
	}

	public String getProcessingTypeCode() {
		return processingTypeCode;
	}

	public void setProcessingTypeCode(String processingTypeCode) {
		this.processingTypeCode = processingTypeCode;
	}

	public HashMap<Integer, Item> getItems() {
		return items;
	}

	public void setItems(HashMap<Integer, Item> items) {
		this.items = items;
	}

	public void insertQuotationElement(Element parentElement) {
		Element CustomerQuote = parentElement.addElement("CustomerQuote");
		CustomerQuote.addElement("ProcessingTypeCode").addText(
				this.getProcessingTypeCode());
		Element BuyerParty = CustomerQuote.addElement("BuyerParty");
		BuyerParty.addElement("InternalID").addText(
				this.getCustomer().getNumber());

		for (Item item : this.getItems().values()) {
			if (item.getProduct() != null) {
				Element itemElement = CustomerQuote.addElement("Item");
				Element product = itemElement.addElement("Product");
				product.addElement("EnteredProductInternalID").addText(
						item.getProduct().getPRODUCT_ID());
				itemElement.addElement("ID").addText(
						Integer.toString(item.getId()));

				Element scheduleLine = itemElement.addElement("ScheduleLine");
				scheduleLine.addElement("TypeCode").addText("CT");
				scheduleLine.addElement("Quantity").addAttribute("unitCode",
						item.getUnit()).addText("" + item.getQuantity());
				scheduleLine.addElement("DateTime").addAttribute(
						"timeZoneCode", "CET").addAttribute(
						"daylightSavingTimeIndicator", "false").addText(
						"2010-01-27T16:32:33");
			}
		}
	}

	@SuppressWarnings("unchecked")
	public String checkQuotation() {
		String webServiceReturnMessage = "";
		Document request = checkQuotationCreateDocument();
		String req = request.asXML();
		req = req + "";
		try {
			HttpURLConnection connection;

			connection = (HttpURLConnection) new URL(endpoint).openConnection();

			Document responseDoc = SoapUtils.request(request, connection,
					username, password);
			String resp = responseDoc.asXML();
			resp = resp + "";
			connection.disconnect();

			String QuoteNumber = "";
			String BusinessDocumentProcessingResultCode = "";
			BusinessDocumentProcessingResultCode = responseDoc
					.selectSingleNode(
							"//Log/BusinessDocumentProcessingResultCode")
					.getText();
			if (BusinessDocumentProcessingResultCode.equalsIgnoreCase("3")) {
				QuoteNumber = responseDoc
						.selectSingleNode("//CustomerQuote/ID").getText();
				System.err.println(QuoteNumber);
				webServiceReturnMessage = "Successfull. QuotationID = "
						+ QuoteNumber;
				// QuoteNumberTextView.setText(QuoteNumber);
			} else {
				webServiceReturnMessage = "Creation of Quotation failed: ";
				// QuoteNumberTextView
				// .setText("BusinessDocumentProcessingResultCode = "
				// + BusinessDocumentProcessingResultCode);
			}

			List<Node> logItems = responseDoc.selectNodes("//Log/Item");
			System.err.println("Log Size " + logItems.size());

			for (Iterator<Node> logIterator = logItems.iterator(); logIterator
					.hasNext();) {
				Node logItem = logIterator.next();
				System.err
						.println(logItem.selectSingleNode("TypeID").getText());
				System.err.println(logItem.selectSingleNode("SeverityCode")
						.getText());
				System.err.println(logItem.selectSingleNode("Note").getText());
				// System.err.println(logItem.selectSingleNode("WebURI").getText());

				webServiceReturnMessage = webServiceReturnMessage + " \n\0";
				webServiceReturnMessage = webServiceReturnMessage + " "
						+ logItem.selectSingleNode("TypeID").getText();
				webServiceReturnMessage = webServiceReturnMessage + " "
						+ logItem.selectSingleNode("SeverityCode").getText();
				webServiceReturnMessage = webServiceReturnMessage + " "
						+ logItem.selectSingleNode("Note").getText();
			}
			return webServiceReturnMessage;
		} catch (SoapException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			return e.getMessage();
		}

	}

	@SuppressWarnings("unchecked")
	public String createQuotation() {
		String webServiceReturnMessage = "";
		Document request = createQuotationCreateDocument();
		String req = request.asXML();
		req = req + "";
		try {
			HttpURLConnection connection;
			connection = (HttpURLConnection) new URL(
					"http://crm.esworkplace.sap.com:80/sap/bc/srt/xip/sap/CRM_BTSQ_CUSTQTECRTRC?sap-client=800")
					.openConnection();

			Document responseDoc = SoapUtils.request(request, connection,
					username, password);
			String resp = responseDoc.asXML();
			resp = resp + "";
			connection.disconnect();

			String BusinessDocumentProcessingResultCode = "";
			BusinessDocumentProcessingResultCode = responseDoc
					.selectSingleNode(
							"//Log/BusinessDocumentProcessingResultCode")
					.getText();
			if (BusinessDocumentProcessingResultCode.equalsIgnoreCase("3")) {
				this.setId(responseDoc.selectSingleNode("//CustomerQuote/ID")
						.getText());
				System.err.println(this.getId());
				webServiceReturnMessage = "Successfull. QuotationID = "
						+ this.getId();
			} else {
				webServiceReturnMessage = "Creation of Quotation failed: ";
			}

			List<Node> logItems = responseDoc.selectNodes("//Log/Item");
			System.err.println("Log Size " + logItems.size());

			for (Iterator<Node> logIterator = logItems.iterator(); logIterator
					.hasNext();) {
				Node logItem = logIterator.next();
				Log.w("Quotation submission: Log", logItem.selectSingleNode(
						"TypeID").getText());
				Log.w("Quotation submission: Log", logItem.selectSingleNode(
						"SeverityCode").getText());
				Log.w("Quotation submission: Log", logItem.selectSingleNode(
						"Note").getText());

				webServiceReturnMessage = webServiceReturnMessage + " \n\0";
				webServiceReturnMessage = webServiceReturnMessage + " "
						+ logItem.selectSingleNode("TypeID").getText();
				webServiceReturnMessage = webServiceReturnMessage + " "
						+ logItem.selectSingleNode("SeverityCode").getText();
				webServiceReturnMessage = webServiceReturnMessage + " "
						+ logItem.selectSingleNode("Note").getText();
			}
			return webServiceReturnMessage;
		} catch (SoapException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (MalformedURLException e) {
			e.printStackTrace();
			return e.getMessage();
		} catch (IOException e) {
			e.printStackTrace();
			return e.getMessage();
		}

	}

	public Document checkQuotationCreateDocument() {
		DocumentFactory factory = DocumentFactory.getInstance();

		Document document = factory.createDocument();
		Element envelope = document.addElement(factory.createQName("Envelope",
				"soapenv", "http://schemas.xmlsoap.org/soap/envelope/"));
		envelope.addElement(factory.createQName("Header", "soapenv",
				"http://schemas.xmlsoap.org/soap/envelope/"));
		Element body = envelope.addElement(factory.createQName("Body",
				"soapenv", "http://schemas.xmlsoap.org/soap/envelope/"));
		Element customerQuoteCRMCreateRequest_sync_V1 = body.addElement(factory
				.createQName("CustomerQuoteCRMCreateCheckQuery_sync", "glob",
						"http://sap.com/xi/CRM/Global2"));
		insertQuotationElement(customerQuoteCRMCreateRequest_sync_V1);
		return document;
	}

	public Document createQuotationCreateDocument() {
		DocumentFactory factory = DocumentFactory.getInstance();

		Document document = factory.createDocument();
		Element envelope = document.addElement(factory.createQName("Envelope",
				"soapenv", "http://schemas.xmlsoap.org/soap/envelope/"));
		envelope.addElement(factory.createQName("Header", "soapenv",
				"http://schemas.xmlsoap.org/soap/envelope/"));
		Element body = envelope.addElement(factory.createQName("Body",
				"soapenv", "http://schemas.xmlsoap.org/soap/envelope/"));
		Element customerQuoteCRMCreateRequest_sync_V1 = body.addElement(factory
				.createQName("CustomerQuoteCRMCreateRequest_sync_V1", "glob",
						"http://sap.com/xi/CRM/Global2"));
		insertQuotationElement(customerQuoteCRMCreateRequest_sync_V1);
		return document;
	}

}
